package rabbit.worker;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Envelope;
import org.apache.log4j.Logger;
import org.springframework.context.support.GenericXmlApplicationContext;
import rabbit.common.ConsumerHandler;


/**
 * Created by root on 17-4-23.
 */
public class workerTester {
    private static Logger LOGGER = Logger.getLogger(workerTester.class.getTypeName());

    public static void main(String[] args){
        if(args==null||args.length==0){
            LOGGER.info("mandatory parameter are missed : W: worker, S: sender");
        }

        loadSpringConfig();
        String type = args[0];
        String name = "default";
        if(args.length==2){
            name = args[1];
        }
        LOGGER.info("name is "+name);

        if(type.toUpperCase().equals("W")){
            startWorker(name);
        }
        if(type.toUpperCase().equals("S")){
            startSender(name);
        }
    }

    private static GenericXmlApplicationContext context;

    private static void loadSpringConfig(){
        context = new GenericXmlApplicationContext();
        context.setValidating(false);
        context.load("classpath*:bean.xml");
        context.refresh();
    }

    private static void startSender(String senderName){
        sender _sender = (sender)context.getBean(senderName);
        if(_sender==null){
            LOGGER.error("sender :"+senderName+" cannot be found, check the config file");
        }
        while(true){
            //System.out.println("Please write down your message : ");
            //String message = System.console().readLine();
            _sender.senMessage("hello world");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                LOGGER.error(e.getMessage());
            }
        }
    }


    private static void startWorker(String workerName){
        worker _worker = (worker)context.getBean(workerName);
        ConsumerHandler handler = new ConsumerHandler() {
            @Override
            public void messageHandler(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String message = new String(body);
                LOGGER.info("External consumer "+" : "+message);
            }
        };
        _worker.setConsumer(handler);
        if(_worker==null){
            LOGGER.error("sender :"+workerName+" cannot be found, check the config file");
        }
        _worker.consumeMessage();
    }
}
